﻿using RpcClient.Interface;
using RpcHelper;
using RpcModularModel.Visit.Model;
using RpcSync.DAL;
using RpcSync.Model;

namespace RpcSync.Collect.DelayData
{
    [RpcClient.Attr.ClassLifetimeAttr(RpcClient.Attr.ClassLifetimeType.单例)]
    internal class VisitCensusDelaySave : IVisitCensusDelaySave
    {
        private readonly IDelayDataSave<RpcVisitCensus> _SyncVisit;

        private IUnityCollect _Unity;
        public VisitCensusDelaySave(IUnityCollect unity)
        {
            _Unity = unity;
            _SyncVisit = new DelayDataSave<RpcVisitCensus>(_Save, _Filter, 2, 10);
        }
        private void _Filter(ref RpcVisitCensus[] datas)
        {
            datas = datas.GroupBy(a => new
            {
                a.ServiceId,
                a.Dictate
            }).Select(a => new RpcVisitCensus
            {
                ServiceId = a.Key.ServiceId,
                Dictate = a.Key.Dictate,
                Success = a.Sum(c => c.Success),
                Fail = a.Sum(c => c.Fail),
                Concurrent = a.Sum(c => c.Concurrent)
            }).ToArray();
        }

        private void _Save(ref RpcVisitCensus[] datas)
        {
            _Unity.Resolve<IServerVisitCensusDAL>().Sync(datas);
        }
        public void AddLog(RpcVisitCensus add)
        {
            _SyncVisit.AddData(add);
        }
    }
}
